<template>
  <div class="p-2">
    <Forms ref="subForm" :data-from="formData" :list="pageSetting.TestTraceLog.search" name="TestTraceLog" :sub-loading="tableLoading" />
    <el-button @click="appendixDownload">{{ translateTitle('Dams.ApplicationInterface.下载附件') }}</el-button>
    <Table
      ref="main_Table"
      :column-list="mainTableColumn"
      :get-height="getHeight"
      :loading="tableLoading"
      name="TestTraceLog"
      :style="{ height: `${getHeight}px` }"
      :tables="tables"
    />
  </div>
</template>
<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import TestTraceLog from '../../components/json/TestTraceLog'
  import { getList, download } from '../../api/home.js'
  import Table from '../../components/table.vue'
  import Forms from '../../components/forms'
  import debounce from 'lodash/debounce'
  import { translateTitle } from '@/utils/i18n'
  export default {
    name: 'TestTraceLog',
    components: { Table, Forms },
    mixins: [Mixin],
    data() {
      return {
        tabLoading: false,
        tabName: 'first',
        pageSetting: {
          TestTraceLog: { search: {} },
        },
        configSetting: {},
        apiParameter: {},
        show: false,
        formData: {},
        tables: {
          tableList: [],
          count: 0,
          pageSize: 150,
          limit: 1,
          name: 'TestTraceLog',
          operation: true,
          formatting: false,
        },
        clientHeight: 0,
        vuiCodevalue: '',
        tableLoading: false,
        unsubs: [],
        sqlList: [],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 180}`
      },
      mainTableColumn() {
        if (this.pageSetting.TestTraceLog.dialog) {
          let arr = this.pageSetting.TestTraceLog.dialog.form.field
          let newArr = []
          arr.forEach((v) => {
            if (v.type != 'button' && v.type != 'line' && !v.tableHidden && v.type != 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name,
                type: v.type,
              })
            }
            if (v.type == 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name.split(',')[0] + ',' + v.name.split(',')[1],
                type: v.type,
              })
            }
          })
          return newArr
        } else {
          return []
        }
      },
    },
    created() {
      this.init()
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    methods: {
      async appendixDownload() {
        console.log(this.$refs, this.$refs['main_Table'].$refs)
        let list = this.$refs['main_Table'].$refs['xTableTestTraceLog'].getCheckboxRecords()
        if (list.length == 0) return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请选择数据'), 'error')
        list.forEach((r) => {
          r.ORG_ID = this.$store.getters['user/getConstant']['#ORG_ID#']
        })
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        let method = 'dams.file.common.download'
        let res = await download(url, {
          data: JSON.stringify(list),
          method: method,
        })
        if (res.size) {
          // 针对下载请求返回失败之后的处理等
          // 将blob转为json
          const reader = new FileReader()
          let parseObj = null
          reader.readAsText(res, 'utf-8')
          reader.onload = () => {
            parseObj = JSON.parse(reader.result)
            console.log(parseObj)
            this.$baseMessage(parseObj.msg, 'error')
          }
        } else {
          let blob = new Blob([res.data])
          console.log(blob)
          let downloadElement = document.createElement('a')
          let href = window.URL.createObjectURL(blob)
          downloadElement.href = href
          downloadElement.download = decodeURI(res.disposition.split("''")[res.disposition.split("''").length - 1])
          document.body.appendChild(downloadElement)
          downloadElement.click()
          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
          console.log(module)
        }
      },
      translateTitle,
      windowResize: debounce(function () {
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      async onSubmit(p) {
        let sub = p ? JSON.parse(JSON.stringify(p)) : []
        let obj = {
          '#LIMIT#': this.tables.limit,
          '#PAGE_SIZE#': this.tables.pageSize,
          ...sub[0],
        }
        if (p.length > 0 && p[0].DATE_TIME) {
          delete obj.DATE_TIME
          obj.DATE_TIME_START = p[0].DATE_TIME[0]
          obj.DATE_TIME_END = p[0].DATE_TIME[1]
        }
        this.tableLoading = true
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: 'system.log.server.document.mark.query',
        })
        this.tableLoading = false
        console.log(res)
        this.tables.tableList = res.data.data.data
        this.tables.count = res.data.data.count
      },
      eventInit() {
        //搜索事件
        this.$sub(`TestTraceLog_forms_on_search`, (data_arr) => {
          console.log(JSON.parse(JSON.stringify(data_arr)))
          this.formData = data_arr[0]
          this.tables.limit = 1
          this.onSubmit(data_arr)
        })
        this.unsubs.push(`TestTraceLog_forms_on_search`)
        this.$sub(`TestTraceLog_Table_on_TestTraceLog`, (page_arr) => {
          this.tables.limit = page_arr[0].limit
          this.tables.pageSize = page_arr[0].pageSize
          this.onSubmit([this.formData])
        })
        this.unsubs.push(`TestTraceLog_Table_on_TestTraceLog`)
      },
      async init() {
        this.configSetting = GFCD('dams')
        // this.nowJsonData().then((data) => {
        this.pageSetting = TestTraceLog
        this.show = true
        this.windowResize()
        this.eventInit()
        // })
      },
    },
  }
</script>
